-- tree_house
-- create by cheny3
-- 树屋

return {
    -- 判断
    canTrigger = function(args)
        -- 找一下当前有没有树屋
        for pos = 1, GRID_SIZE do
            local grid = DungeonM.getGridByPos(pos);
            if grid.type == GRID_TYPE_TREE_HOUSE then
                return true;
            end
        end
        return false;
    end,

    -- 触发
    trigger = function(args)
        -- 获取树屋pos
        local treeHouse;
        local treePos;
        for pos = 1, GRID_SIZE do
            local grid = DungeonM.getGridByPos(pos);
            if grid.type == GRID_TYPE_TREE_HOUSE then
                treeHouse = grid.tree_house;
                treePos = pos;
                break;
            end
        end
        if not treeHouse then
            return false;
        end

        -- 没有激活的话，尝试激活
        if not treeHouse:isActive() then
            local items = {};
            local skills = TreeHouseM.getAllSkills();
            for _, info in pairs(skills) do
                local classId = info.class_id;
                if ItemM.getAmount(ME.user, classId) > 0 then
                    table.insert(items, classId);
                end
            end

            if #items < 4 then
                -- 不足以激活
                return false;
            end

            -- 随机选4个提交
            for i = 1, 4 do
                local index = math.random(#items);
                DungeonActionM.go("tree_house_submit", treePos, items[index]);
                table.remove(items, index);
            end
        else
            -- 激活了，尝试升级技能
            local allSkills = treeHouse:getAllSkills();
            for skillId, _ in pairs(allSkills) do
                if TreeHouseM.canUpgradeSkill(skillId) == true then
                    return DungeonActionM.go("upgrade_tree_house_skill", skillId);
                end
            end
            -- 没有一个可以升级的
            return false;
        end

        return true;
    end,
};
